<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="机构编号" prop="orgCode">
        <el-input
          v-model="queryParams.orgCode"
          placeholder="请输入机构编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机构名称" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入机构名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属业务" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择所属业务" clearable>
          <el-option
            v-for="dict in business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="上级机构" prop="parentOrgId" label-width="100px">
          <el-cascader
            v-model="queryParams.parentOrgId"
            :options="organizationOptions"
            :props="cascaderProps"
            placeholder="请选择上级机构"
            clearable
            filterable
            style="width: 100%">
          </el-cascader>
        </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:organization:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['service:organization:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['service:organization:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['service:organization:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="organizationList" @selection-change="handleSelectionChange" @row-dblclick="handleRowDbClick">
      <el-table-column label="" align="center" type="index" width="50" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="机构编号" align="center" prop="orgCode" />
      <el-table-column label="机构名称" align="center" prop="orgName" />
      <el-table-column label="所属业务" align="center" prop="businessType">
        <template #default="scope">
          <dict-tag :options="business_type" :value="scope.row.businessType"/>
        </template>
      </el-table-column>
      <el-table-column label="上级机构" align="center" width="150">
        <template #default="scope">
          {{ getParentOrgName(scope.row.parentOrgId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['service:organization:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['service:organization:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改机构管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body draggable 
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false">
      <el-form ref="organizationRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="机构编号" prop="orgCode">
          <el-input v-model="form.orgCode" placeholder="请输入机构编号" />
        </el-form-item>
        <el-form-item label="机构名称" prop="orgName">
          <el-input v-model="form.orgName" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item label="所属业务" prop="businessType">
          <el-select v-model="form.businessType" placeholder="请选择所属业务">
            <el-option
              v-for="dict in business_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级机构" prop="parentOrgId">
          <el-cascader
            v-model="form.parentOrgId"
            :options="organizationOptions"
            :props="cascaderProps"
            placeholder="请选择上级机构"
            clearable
            filterable
            style="width: 100%">
          </el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Organization">
import { listOrganization, getOrganization, delOrganization, addOrganization, updateOrganization } from "@/api/service/organization"
import { cascaderProps, organizationOptions, getOrganizationList, getParentOrgName } from "@/api/common"

const { proxy } = getCurrentInstance()
const { business_type } = proxy.useDict('business_type')

const organizationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")


const props = defineProps({
  isModal: {
    type: Boolean,
    default: true
  },
  center: {
    type: Boolean,
    default: true
  }
})

const currentSelected = ref({})
const emit = defineEmits(['select'])


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orgCode: null,
    orgName: null,
    businessType: null,
    parentOrgId: null,
  },
  rules: {
    orgCode: [
      { required: true, message: "机构编号不能为空", trigger: "blur" }
    ],
    orgName: [
      { required: true, message: "机构名称不能为空", trigger: "blur" }
    ]
  }
})



const { queryParams, form, rules } = toRefs(data)

/** 查询机构管理列表 */
function getList() {
  loading.value = true

  listOrganization(queryParams.value).then(responses => {
    organizationList.value = responses.rows
    total.value = responses.total
    loading.value = false
    
    // 保存所有机构信息
    //allOrganizations.value = responses.rows
  })

  getOrganizationList()
}

/* function getList() {
  loading.value = true
  Promise.all([
    listOrganization(queryParams.value),
    listOrganization({}, false) // 获取所有机构用于级联选择器
  ]).then(responses => {
    organizationList.value = responses[0].rows
    total.value = responses[0].total
    loading.value = false
    
    // 保存所有机构信息
    allOrganizations.value = responses[1].rows
    
    // 构建级联选择器数据
    const allOrganizations2 = responses[1].rows
    organizationOptions.value = buildOrganizationTree(allOrganizations2)
  })
} */





// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orgCode: null,
    orgName: null,
    businessType: null,
    parentOrgId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    deleted: null
  }
  proxy.resetForm("organizationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length

  if (selection.length > 0) 
     currentSelected.value = selection[0]
}

/* // 多选框选中数据（实现单选行为）
function handleSelectionChange(selection) {
  // 如果选择了多个，则只保留最后一个
  if (selection.length > 1) {
    // 清除所有选择
    proxy.$refs.tableRef?.clearSelection()
    // 只选择最后一个
    proxy.$refs.tableRef?.toggleRowSelection(selection[selection.length - 1], true)
    selection = [selection[selection.length - 1]]
  }
  
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
  
  // 记录当前选择项
  if (selection.length === 1) {
    currentSelected.value = selection[0]
  }
} */

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加机构管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrganization(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改机构管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["organizationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrganization(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrganization(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除机构管理编号为"' + _ids + '"的数据项？').then(function() {
    return delOrganization(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/organization/export', {
    ...queryParams.value
  }, `organization_${new Date().getTime()}.xlsx`)
}

// 双击行事件
function handleRowDbClick(row) {
  if (!props.isModal) {
    emit('select', row)
  }
}

// 确认选择
function handleSelectConfirm() {
  if (Object.keys(currentSelected.value).length > 0) {
    emit('select', currentSelected.value)
  }
}

getList()

// 向外暴露方法
defineExpose({
  handleSelectConfirm
})
</script>
